package jiaoheng;

import org.junit.Test;

public class Search {
    /*
    二分查找时，
    需要考虑边界行为，永远达不到边界的值怎么办
     */
    @Test
    public void binarySearchTest(){
        int[] arr = {1,2,3,4,5,6,7,8};
        int index = binarySearch(arr,8);
        System.out.println(index);

    }
    public int binarySearch(int[] arr,int targetValue){
        int targetValueIndex = -1;
        if (arr == null || arr.length == 0) {
            return -1; // 处理空数组情况
        }
        int leftIndex=0;
        int rightIndex=arr.length-1;
        while(leftIndex<=rightIndex){
            int middleIndex = (leftIndex+rightIndex)/2;
            if(arr[middleIndex]==targetValue){
                return middleIndex;
            }else if(arr[middleIndex]>targetValue){
                rightIndex=middleIndex-1;
            }else{
                leftIndex=middleIndex+1;
            }
        }
        return targetValueIndex;
    }
}
